package com.ruike.alisurface.ui.payPage;

import android.os.Bundle;
import android.os.SystemClock;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.ruike.alisurface.Constant;
import com.ruike.alisurface.R;
import com.ruike.alisurface.Serials.MsgEventBus;
import com.ruike.alisurface.Serials.ShopInfoUtils;
import com.ruike.alisurface.Serials.outGoods.ShopChUtils;
import com.ruike.alisurface.base.BaseAty;
import com.ruike.alisurface.bean.ShopDetailBean;
import com.ruike.alisurface.bean.rkAdBean;
import com.ruike.alisurface.http.MchApiHttp;
import com.ruike.alisurface.ui.answerQuestion.http.TongNuoHttp;
import com.ruike.alisurface.ui.mainPage.MainActivity;
import com.ruike.alisurface.utils.AdvDialogUtils;
import com.ruike.alisurface.utils.BackMainUtils;
import com.ruike.alisurface.utils.GlideImageLoader;
import com.ruike.alisurface.utils.ShareKey;
import com.ruike.alisurface.utils.ThreadUtils;
import com.voodoo.lib_utils.GsonUtils;
import com.voodoo.lib_utils.L;
import com.voodoo.lib_utils.ShareUtils;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;

import static com.ruike.alisurface.utils.ShareKey.IC2_SLOT_NUM;
import static com.ruike.alisurface.utils.ShareKey.Type_Chshopzl;
import static com.ruike.alisurface.utils.ShareKey.Type_Chshopzl_OLD;
import static com.ruike.alisurface.utils.ShareKey.Type_Chshopzl_SIXOLD;

/**
 * 支付出货页
 */
public class PayShowShopActivity extends BaseAty {

    @BindView(R.id.ali_card_count_time)
    TextView selectPayCountDownTv;
    @BindView(R.id.adv_hd_img)
    ImageView adv_hd_img;
    ShopDetailBean paycarlist;//商品 集合
    double monery = 0.00;//总金额
    int outGoodsNumber = 0; // 升降机出货数量回调计数

    volatile int shopcount = 0;//出货数量
    List<String> serialList = new ArrayList<>();//货道串口返回值集合
    Timer timer = new Timer();//计时
    private String paytype;//支付类型
    boolean isSuccess = true;//是否出货成功
    List<ShopInfoUtils.slotBean> slotBeanList = new ArrayList<>();//货道指令集合
    List<ShopInfoUtils.slotBean> slotTypeList = new ArrayList<>();//货道类型集合

    List<String> mImgs = new ArrayList<>();

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_rk_showshop;
    }

    @Override
    protected void initViews() {
        initTitleBar(false);
        L.iTag("toshop", "支付出货页==" + this.getClass().getName());

        adv_hd_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AdvDialogUtils.AliHuoDongDialog(PayShowShopActivity.this, mImgs);
            }
        });
    }


    @Override
    protected void initData() {
        paytype = getIntent().getExtras().getString("pay_type");
        paycarlist = (ShopDetailBean) getIntent().getSerializableExtra("orderBeanData");
        if (paycarlist == null) {
            showErrorTip("传入的数据为空");
            startCountdownTimer(3, null, null);
            return;
        }
        String order_code = ShareUtils.getInstance().getString(ShareKey.ORDER_RESULT, "");
        L.iTag("出货  页==order_code= ", "上次的单号==" + order_code);
        if (!TextUtils.isEmpty(order_code) && order_code.equals(paycarlist.getOrderId())) {
            L.iTag("出货  页=== ", "多次出货，订单号已经出货过 无法再次出货 回到主页面");
            BackMainUtils.setActivity(this);
            finish();
            return;
        }

        for (int i = 0; i < paycarlist.getDetailOrderList().size(); i++) {
            monery += Double.valueOf(paycarlist.getDetailOrderList().get(i).getPrice());
            shopcount += paycarlist.getDetailOrderList().get(i).getQuantity();

        }
        L.iTag("toshop", "出货数量--" + shopcount);


        int time_shopcount = shopcount;
        if (time_shopcount > 0) {
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    L.iTag("toshop", " 计时结束出货页面--");
                    shopcount = 0;
                    todoPageAty();
                }
            }, 15000 * time_shopcount);
        }

        if (paycarlist.getDetailOrderList().size() > 0) {
            PutGoods();
        }
    }

    Runnable ShopRunable = new Runnable() {
        @Override
        public void run() {
            try {
                List<ShopDetailBean.OrderDetailsBean> detailList = paycarlist.getDetailOrderList();
                int size = detailList.size();
                for (int i = 0; i < size; i++) {
                    if (paycarlist == null) {
                        return;
                    }
                    int type = detailList.get(i).getSlotTypeId();
                    int index = detailList.get(i).getSlotIndex();
                    int count = detailList.get(i).getQuantity();
                    L.iTag("toshop", "tjf==" + "run: 出货货道："
                            + index + "出货类型==" + type + "==出货数量=" + count);
                    for (int j = 0; j < count; j++) {
                        if (paycarlist == null) {
                            return;
                        }
                        ShopInfoUtils.slotBean slotype = new ShopInfoUtils.slotBean();
                        slotype.setSlot(String.valueOf(index));
                        if (type == 21001) {  //弹簧货到
                            slotype.setTypes(0);
                        } else if (type == 21002) {//蛇形货道
                            slotype.setTypes(2);
                        } else if (type == 21003) {//电磁锁
                            slotype.setTypes(1);
                        }
                        slotTypeList.add(slotype);
                        ShopChUtils.shopTodo(type, index);
                    }
                }
            } catch (Exception e) {
                L.iTag("toshop", "出货页未知退出  Exception==" + e.getMessage());
            }
        }
    };

    /**
     * 出货方法
     */
    private void PutGoods() {
        try {
            // 判断数据是否已经存在
            ThreadUtils.postDelayed(ShopRunable, 2000);

        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        Constant.isMQTTshop = false;
        Constant.showShop = true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        MchApiHttp.getrk_ad(this);
        startCountdownTimer(120, selectPayCountDownTv, null);
    }

    @Override
    protected void onStop() {
        super.onStop();
        ThreadUtils.removes(ShopRunable);
        setTimerCancel();
        paycarlist = null;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        L.iTag("toshop", "onDestroy 出货页销毁 ");
        Constant.showShop = false;

    }

    public void setTimerCancel() {
        if (timer != null) {
            timer.purge();
            timer.cancel();
            timer = null;
        }
    }

    @Override
    public void onSuccess(String requestUrl, String requestJsonStr) {
        super.onSuccess(requestUrl, requestJsonStr);
        if (requestUrl.endsWith("get_rk_ad")) {
            rkAdBean rkAdBean = GsonUtils.json2Model(requestJsonStr, rkAdBean.class);
            ShareUtils.getInstance().putBoolean(ShareKey.GET_RK_AD, true);
            adv_hd_img.setVisibility(View.VISIBLE);
            String outadv = rkAdBean.getData().getOutgoods_banner();
            String Name = outadv.substring(outadv.lastIndexOf("/")).substring(1);
            File file = new File(Constant.topAdvpath, Name);
            L.i("topadv", "本地图片是否存在==" + file.exists());
            GlideImageLoader.loadImage(this, file.exists() ? file.getAbsolutePath() : rkAdBean.getData().getOutgoods_banner(), adv_hd_img);
            mImgs.clear();
            mImgs.add(rkAdBean.getData().getAlert_page());
            return;
        }
        if (TongNuoHttp.CONFIRM_QUESTION_ORDER_URL.contentEquals(requestUrl) || requestUrl.endsWith("OrderIsEnd") || requestUrl.endsWith("Rk_Card_EndOrder")) {
            L.iTag("toshop", "OrderIsEnd   onSuccess === +出貨完成");
            todoPage();
        }
    }

    @Override
    public void onError(String requestUrl, String errorMsg) {
        super.onError(requestUrl, errorMsg);
        if (requestUrl.endsWith("get_rk_ad")) {
            ShareUtils.getInstance().putBoolean(ShareKey.GET_RK_AD, false);
            adv_hd_img.setVisibility(View.GONE);
            return;
        }
        if (TongNuoHttp.CONFIRM_QUESTION_ORDER_URL.contentEquals(requestUrl) || requestUrl.endsWith("OrderIsEnd") || requestUrl.endsWith("Rk_Card_EndOrder")) {
            L.iTag("toshop", "OrderIsEnd   onError === +出貨失敗");
            todoPage();
        }
    }

    /**
     * 相关信息及跳转下一页
     */
    public void todoPage() {
        if (paycarlist == null) {
            return;
        }
        Bundle bundle = getIntent().getExtras();
        paytype = bundle.getString("pay_type", "wechat");
        L.iTag("出货  页=", "写入订单号" + paycarlist.getOrderId());

        ShareUtils.getInstance().putString(ShareKey.ORDER_RESULT, paycarlist.getOrderId());

        bundle.putString("order_id", paycarlist.getOrderId());
        bundle.putDouble("order_money", paycarlist.getTotal_fee());
        bundle.putDouble("actual_money", paycarlist.getPay_fee());

        if (slotBeanList.size() > 0) {
            bundle.putBoolean("isSuccess", isSuccess);
            bundle.putSerializable("slotList", (Serializable) slotBeanList);
        } else {
            bundle.putBoolean("isSuccess", isSuccess);
        }

        if (paytype.equals("wechat")) {
            bundle.putDouble("discount", paycarlist.getPromotion_fee());
        } else if (paytype.equals("alface")) {
            bundle.putDouble("discount", paycarlist.getDiscount_fee());
        } else if (paytype.equals("weCard")) {

        }
        startActivity(PayfaceSuccessActivity.class, bundle);
        finish();
    }

    boolean isold;//是否是旧的指令  06  的长度

    @Override
    public void doEventBusResult(MsgEventBus event) {
        if (event.getType().equals(Type_Chshopzl) || event.getType().equals(Type_Chshopzl_OLD)) {
            L.iTag("toshop", "每一次的返回值");
            ShopChUtils.setPutflag(false);
            serialList.add(event.getMessage());
            return;
        }
        if (event.getType().equals(Type_Chshopzl_SIXOLD)) {
            L.iTag("toshop", "每一次的返回值");
            ShopChUtils.setPutflag(false);
            isold = true;
            return;
        }
        if (event.getType().equals("出货倒计时完成") || event.getType().equals("出货倒计时未完成")) {
            --shopcount;
            L.iTag("toshop", " 出货数量递减======" + shopcount);
            todoPageAty();
            return;
        }
    }


    /**
     * 解析指令及上传完结信息
     */
    public void todoPageAty() {

        L.iTag("toshop", " 计时  出货数量--", shopcount, "开始上传信息及跳转完成页");
        if (paycarlist == null) {
            return;
        }
        if (shopcount == 0) {
            shopcount = -1;
            setTimerCancel();
            String datas = "";
            if (!isold) {
                if (serialList.size() > 0) {
                    ShopInfoUtils.dllist.clear();
                    for (int i = 0; i < serialList.size(); i++) { //外层获取指令
                        String[] data_code = serialList.get(i).split(" ");
                        int slot_num = ShareUtils.getInstance().getInt(IC2_SLOT_NUM, 100);//得到每一个柜子的最大货道
                        int index = ((Integer.parseInt(data_code[0]) - 10) * slot_num) + Integer.parseInt(data_code[5], 16) + 1;
                        for (int s = 0; s < slotTypeList.size(); s++) {//内层获取货道出货类型
                            if (slotTypeList.get(s).getSlot().equals(index + "")) {
                                ShopInfoUtils.analyzeSlot(serialList.get(i), slotTypeList.get(s).getTypes());
                                break;
                            }
                        }
                    }
                    datas = GsonUtils.ListtoString(serialList);
                    if (ShopInfoUtils.dllist.size() > 0) {
                        for (ShopInfoUtils.slotBean slotBean : ShopInfoUtils.dllist) {
                            if (slotBean.getZdcount() < slotBean.getSlotCount()) {
                                slotBeanList.add(slotBean);
                                isSuccess = false;
                            }
                        }
                    } else {
                        isSuccess = false;
                    }
                    ShopInfoUtils.sendCheckoutnotify(paycarlist.getOrderId());
                } else {
                    isSuccess = false;
                }
                serialList.clear();
            }
            SystemClock.sleep(100);
            HashMap<String, Object> map = new HashMap<>();
            map.put("OrderNo", paycarlist.getOrderId());
            map.put("IsEnd", isSuccess);
            map.put("Remark", datas + "完成");
            L.iTag("toshop", "开始完成接口");
            if (paytype.equals("weCard")) {
                MchApiHttp.rkCardEndOrder(paycarlist.getOrderId(), isSuccess, datas + "完成", this);
            } else if ("ansertQuestion".equals(paytype)) {
                TongNuoHttp.questionEndOrder(paycarlist.getOrderId(), isSuccess, datas + "完成", this);
            } else {
                MchApiHttp.getOrderIsEnd(this, map);
            }
        }
    }
}
